#ifdef __APPLE__
    #include <SDL/SDL.h>
#else
    #include <SDL/SDL.h>
#endif
#include "BM_input.h"

BMKeyboard::BMKeyboard(){
    int i = 0;

	for( i = 0; i < 322 + 1; i++) { //SDLK_UNDO = 322
        keys[i] = 0;
	}
}

/*******************************************************************************/
void BMKeyboard::poll(){
    Uint8 *keystates = SDL_GetKeyState( NULL );
	int i;
	for( i = 0; i < 322 + 1; i++){ //322 = SDL_UNDO
		if(keystates[i]) {
			keys[i]++;
		}
		else
			if(keys[i] >= 1)
				keys[i] = -1;
			else
				keys[i] = 0;
	}

	free(keystates);
}

/*******************************************************************************/

int BMKeyboard::hold(int key){
	if(keys[key] > 1)
        return keys[key];
	return 0;
}


/*******************************************************************************/
// key has been pressed
int BMKeyboard::press(int key){
	if(keys[key] == 1)
        return 1;
	return 0;

}

/*******************************************************************************/
// key has been released
int BMKeyboard::release(int key){
	if(keys[key] == -1)
        return 1;
	return 0;
}


/*******************************************************************************/
void BMKeyboard::freeKeyboard(){
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

BMJoystick::BMJoystick(){
	if( SDL_NumJoysticks() < 1 ){
        joystick = false;    
    }else{
		joystick = true;
		stick = SDL_JoystickOpen( 0 );
	}
    int i = 0;
	for( i = 0; i < 20; i++) {
        buttons[i] = 0;
	}
}

BMJoystick::BMJoystick(int n){
	if( SDL_NumJoysticks() < 1 + n ){
        joystick = false;    
    }else{
		joystick = true;
		stick = SDL_JoystickOpen( n );
	}
    int i = 0;

	for( i = 0; i < 20; i++) {
        buttons[i] = 0;
	}
}

/*******************************************************************************/
void BMJoystick::poll(){
	int i;
	for( i = 0; i < 20; i++){ 
		if(SDL_JoystickGetButton(stick, i ))
			buttons[i] ++;
		else
			if(buttons[i] >= 1)
				buttons[i] = -1;
			else
				buttons[i] = 0;
	}

}

/*******************************************************************************/

int BMJoystick::hold(int key){
	if(buttons[key] > 1)
        return buttons[key];
	return 0;
}


/*******************************************************************************/
// key has been pressed
int BMJoystick::press(int key){
	if(buttons[key] == 1)
        return 1;
	return 0;

}

/*******************************************************************************/
// key has been released
int BMJoystick::release(int key){
	if(buttons[key] == -1)
        return 1;
	return 0;
}
